package com.quectel.sdk.zlm;

import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.sdk.zlm.basemodel.ZLMediaKitBaseResp;
import com.quectel.sdk.zlm.constant.ZlmMediaKitConstants;
import com.quectel.util.ex.CheckErrorException;
import com.quectel.util.http.HttpRestUtils;
import lombok.Getter;

import java.util.Map;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2022-10-19 11:01:00
 */
public class ZlmMediaKitRequester {

    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getTrustSSLInstance();

    @Getter
    private final String url;
    @Getter
    private final String secret;

    private ZlmMediaKitRequester(String url, String secret) {
        this.url = url;
        this.secret = secret;
    }

    public static ZlmMediaKitRequester getInstance(String url, String secret) {

        return new ZlmMediaKitRequester(url, secret);
    }

    public <T extends ZLMediaKitBaseResp> T post(String path, Map<String, Object> params, TypeReference<T> typeReference) {
        if (this.url == null) {
            throw new CheckErrorException("checked url " + url + " is null");
        }
        if (this.secret == null) {
            throw new CheckErrorException("checked secret " + secret + " is null");
        }
        params.put("secret", this.secret);
        T response = HTTP_REST_UTILS.post(url + path, params, null, typeReference).getRight();
        if (response.getCode() == ZlmMediaKitConstants.RespCodeEnum.AUTH_FAILED.getCode()) {
            params.put("secret", ZlmMediaKitConstants.DEFAULT_SECRET);
            response = HTTP_REST_UTILS.post(url + path, params, null, typeReference).getRight();
        }
        return response;

    }
}
